//
//  MahjongMachineView.m
//  Mahjong
//
//  Created by 饶首建 on 17/6/30.
//  Copyright © 2017年 com.ikamobile.com. All rights reserved.
//

#import "MahjongMachineView.h"
#import "HWPopTool.h"

#import <GizWifiSDK/GizWifiSDK.h>

typedef enum : NSUInteger {
    BtnTapType_OPEN,
    BtnTapType_DICE,
    BtnTapType_CLOSE,
} BtnTapType;

@interface MahjongMachineView()<UIGestureRecognizerDelegate,GizWifiSDKDelegate,GizWifiDeviceDelegate>

@property (nonatomic,copy) NSString *uid;
@property (nonatomic,copy) NSString *token;
@property (nonatomic,strong) GizWifiDevice *device;

@property (nonatomic,assign) BOOL key5;
@property (nonatomic,assign) BOOL key3;
@property (nonatomic,assign) BOOL key4;

@property (nonatomic,assign) BtnTapType btnTapType;

@property (weak, nonatomic) IBOutlet UIButton *openCloseBtn;
@property (weak, nonatomic) IBOutlet UIView *openCloseView;

@end

static NSString *kAppId = @"64eb58cff6764372bfeeda85ed4202ba";
static NSString *kAppSecret = @"c01ef05d9af14e35a891e69b5d46f328";

@implementation MahjongMachineView

- (void)awakeFromNib{
    [super awakeFromNib];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithActionBlock:^(id  _Nonnull sender) {
        [[HWPopTool sharedInstance]closeWithBlcok:^{}];
    }];
    [self addGestureRecognizer:tap];
    
    [GizWifiSDK sharedInstance].delegate = self;
    [GizWifiSDK setLogLevel:GizLogPrintI];
    //    [GizWifiSDK disableLAN:NO];
    [GizWifiSDK startWithAppID:kAppId appSecret:kAppSecret specialProductKeys:nil cloudServiceInfo:nil autoSetDeviceDomain:NO];
    //匿名登录
    [[GizWifiSDK sharedInstance] userLoginAnonymous];
//    [[GizWifiSDK sharedInstance] userLogin:@"18181902760" password:@"yb123456"];
    
    UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc]initWithActionBlock:^(id  _Nonnull sender) {
        UILongPressGestureRecognizer *gesture = sender;
        if (gesture.state == UIGestureRecognizerStateBegan) {
            [self openFunc];
        }
    }];
    longTap.minimumPressDuration = 1.5f;
    [_openCloseView addGestureRecognizer:longTap];
    
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithActionBlock:^(id  _Nonnull sender) {
        [self openOnceFunc];
    }];
    [_openCloseView addGestureRecognizer:tap1];
    
}

+(instancetype)mahjongMachineView{
    return [[[NSBundle mainBundle] loadNibNamed:@"MahjongMachineView"
                                          owner:nil options:nil]lastObject];
}

- (void)openFunc{ //强起
    _btnTapType = BtnTapType_OPEN;
    [self.device write:@{@"key4":@YES} withSN:4];
    [self.device write:@{@"key5":@YES} withSN:5];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.device write:@{@"key4":@NO} withSN:4];
        [self.device write:@{@"key5":@NO} withSN:5];
    });

}

- (IBAction)diceAction:(id)sender {
    //掷骰子
    _btnTapType = BtnTapType_DICE;
    [self.device write:@{@"key3":@YES} withSN:3];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.device write:@{@"key3":@NO} withSN:3];
    });

}

- (void)openOnceFunc{ //开和关
    [self.device write:@{@"key5":@YES} withSN:5];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.device write:@{@"key5":@NO} withSN:5];
    });
}

- (IBAction)closeAction:(id)sender {
    //开关
    //key4或key5
    _btnTapType = BtnTapType_CLOSE;
    [self.device write:@{@"key5":@YES} withSN:5];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.device write:@{@"key5":@NO} withSN:5];
    });

}
- (IBAction)btnCloseAction:(id)sender {
    [[HWPopTool sharedInstance]closeWithBlcok:^{}];
}

#pragma mark - GizWifiDeviceDelegate
- (void)device:(GizWifiDevice *)device didReceiveData:(NSError *)result data:(NSDictionary *)dataMap withSN:(NSNumber *)sn{
    NSDictionary *dic = dataMap[@"data"];
    Log(@"---------> didReceiveData:%@",dic);
    if (dic != nil && [dic isKindOfClass:[NSDictionary class]]){
        _key3 = [dic[@"key3"]boolValue];
        _key4 = [dic[@"key4"]boolValue];
        _key5 = [dic[@"key5"]boolValue];
        /*
        if (_btnTapType == BtnTapType_OPEN && _key4 && _key5) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.device write:@{@"key4":@NO} withSN:4];
                [self.device write:@{@"key5":@NO} withSN:5];
            });
        }
        if (_btnTapType == BtnTapType_DICE && _key3) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.device write:@{@"key3":@NO} withSN:3];
            });
        }
        if (_btnTapType == BtnTapType_CLOSE && _key5) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.device write:@{@"key4":@NO} withSN:4];
                [self.device write:@{@"key5":@NO} withSN:5];
            });
        }
         */
    }
}


#pragma mark - GizWifiSDKDelegate

- (void)wifiSDK:(GizWifiSDK *)wifiSDK didNotifyEvent:(GizEventType)eventType eventSource:(id)eventSource eventID:(GizWifiErrorCode)eventID eventMessage:(NSString *)eventMessage{
    if(eventType == GizEventSDK) {
        // SDK发生异常的通知
        NSLog(@"SDK event happened: [%@] = %@", @(eventID), eventMessage);
        
        NSArray *devList = [GizWifiSDK sharedInstance].deviceList;
        Log(@"%@",devList);
        
    } else if(eventType == GizEventDevice) {
        // 设备连接断开时可能产生的通知
        GizWifiDevice* mDevice = (GizWifiDevice*)eventSource;
        NSLog(@"device mac %@ disconnect caused by %@", mDevice.macAddress, eventMessage);
    } else if(eventType == GizEventM2MService) {
        // M2M服务返回的异常通知
        NSLog(@"M2M domain %@ exception happened: [%@] = %@", (NSString*)eventSource, @(eventID), eventMessage);
    } else if(eventType == GizEventToken) {
        // token失效通知
        NSLog(@"token %@ expired: %@", (NSString*)eventSource, eventMessage);
    }
}
- (void)wifiSDK:(GizWifiSDK *)wifiSDK didDiscovered:(NSError *)result deviceList:(NSArray *)deviceList {
    // 提示错误原因
    if(result.code != GIZ_SDK_SUCCESS) {
        NSLog(@"result: %@", result.localizedDescription);
    }
    // 显示变化后的设备列表
    NSLog(@"discovered deviceList: %@", deviceList);
    for (GizWifiDevice *dev in deviceList) {
        if ([dev.did isEqualToString:@"kdy2Ai5G73moWSeDXL6vas"]) {
            _device = dev;
        }
    }
    if ([_device.did isEqualToString:@"kdy2Ai5G73moWSeDXL6vas"]) {
        if (_device.netStatus == GizDeviceOnline || _device.netStatus == GizDeviceControlled) {
            _device.delegate = self;
            [_device setSubscribe:nil subscribed:YES];//订阅
        }
        if (_openOnce) {
            _openOnce = NO;
            [self openOnceFunc];
        }
    }
}

- (void)wifiSDK:(GizWifiSDK *)wifiSDK didUserLogin:(NSError *)result uid:(NSString *)uid token:(NSString *)token {
    Log(@"%@",result);
    //注册设备
//        [[GizWifiSDK sharedInstance] bindDeviceWithUid:uid token:token did:@"EgVz3ZVEtCLvAvzNAeKnBh" passCode:@"123456" remark:nil];
//        [[GizWifiSDK sharedInstance] bindRemoteDevice:uid token:token mac:@"60019410880e" productKey:@"f3045d48f1b04831a8f3ac7787a711e6" productSecret:@"a3cd3641d4334980b8735a6cad21ef17"];
    
    //主动刷新绑定设备列表、指定筛选的设备productKey
    [[GizWifiSDK sharedInstance] getBoundDevices:uid token:token specialProductKeys:nil];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    // 取消响应手势
    if (touch.view == self){
        return YES;
    }
    return NO;
}

@end
